package com.zzb.framework.common;

import com.zzb.framework.role.vo.UserLoginVo;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Web 控制器基类
 */
public abstract class AuthController<T extends UserLoginVo> extends Base {
    protected final static int SUCCESS = 1;
    protected final static int FAIL = 0;
    protected final static String DEFAULT_PAGE_INDEX = "0";
    protected final static String DEFAULT_PAGE_SIZE = "10";
    protected final static String MAX_PAGE_SIZE = "100";

    abstract public String getSessionKey();

    /**
     * 获取当前用户
     */
    public T getCurrentUser(HttpServletRequest request) {
        try {
            return (T) request.getSession().getAttribute(getSessionKey());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 注销当前用户
     */
    public void removeUserSession(HttpServletRequest request) {
        request.getSession().removeAttribute(getSessionKey());
    }

    /**
     * 保存/更新session并返回sessionId
     */
    public void saveUserSession(HttpServletRequest request, T t) {
        request.getSession().setAttribute(getSessionKey(), t);
    }


    @InitBinder
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) throws Exception {
        //对于需要转换为Date类型的属性，使用DateEditor进行处理
        binder.registerCustomEditor(Date.class, new DateEditor());
    }

}
